#include "VxIrrLib.h"

//============================================================================
//! initialize and load from xml file
RCODE EngineConfig::Startup( const char * pConfigXmlFileName )
{
	m_strConfigFile = pConfigXmlFileName;
	Reset(); // initialize all values to default
	// read any values set in the config file
	RCODE rc = ReadConfig();
	if( rc )
	{
		// attempt again but write out defaults then read in
		WriteConfig();
		rc = ReadConfig();
	}
	return rc;
}
//============================================================================
//! shutdown
RCODE EngineConfig::Shutdown( void )
{
	return 0;
}

//============================================================================
//! reset settings to default
void EngineConfig::Reset( void )
{
	// graphics
	m_f32Gravity			= 0;

}
//============================================================================
//! read settings from file
RCODE EngineConfig::ReadConfig( void )
{
	// open the config xml file
	TiXmlDocument oDocument( m_strConfigFile.c_str() );
	if( 0 == oDocument.LoadFile()) 
	{
		log_msg( 0, "EngineConfig: Failed loading config file %s\n", m_strConfigFile.c_str() );
		return -1;
	}
	TiXmlElement * poConfigElement = oDocument.FirstChildElement("config");
	if( NULL == poConfigElement )
	{
		log_msg( 0, "EngineConfig: config branch not found\n" );
		return -1;
	}

	// get graphics config
	TiXmlElement * poPhysicsElement = poConfigElement->FirstChildElement("physics");
	if( NULL == poPhysicsElement )
	{
		log_msg( 0, "EngineConfig: physics entry not found\n" );
		return -1;
	}
	// graphics
	if( poPhysicsElement ) 
	{
		TiXmlElement * poCurElement;

		// Get screen attributes
		poCurElement = poPhysicsElement->FirstChildElement("gravity");
		if(poCurElement) 
		{
			poCurElement->QueryFloatAttribute( "force", &m_f32Gravity );
		}
	}

	// get misc attributes
	TiXmlElement * poMiscElement = poConfigElement->FirstChildElement("misc");
	if( poMiscElement ) 
	{
	}
	return 0;
}
//============================================================================
//! write settings from file
RCODE EngineConfig::WriteConfig( void )
{
	TiXmlDocument oDocument;

	// create header
	oDocument.LinkEndChild(new TiXmlDeclaration("1.0", "", ""));
	
	TiXmlElement * poConfigElement = new TiXmlElement("config");
	poConfigElement->SetAttribute("version", "1.0");
	oDocument.LinkEndChild( poConfigElement );

	// physics
	TiXmlElement * poPhysicsElement = new TiXmlElement("physics");
	poConfigElement->LinkEndChild( poPhysicsElement );

	// gravity settings
	TiXmlElement * poScreenElement = new TiXmlElement("gravity");
	poScreenElement->SetDoubleAttribute("force", m_f32Gravity );



	// Write file
	if( false == oDocument.SaveFile( m_strConfigFile.c_str() ) )
	{
		return -1;
	}
	return 0;
}

